/**
 * Created by JetBrains WebStorm.
 * User: LXJ
 * Date: 12-2-10 上午11:21
 * Mail: louxiaojian@gmail.com
 */
(function(S){
    function scrollbar(scrollPanel,s,under){
        /*
         *参数设置
         */
        var s = s || {},
            scrollType = s.scrollType || 'x',
            size = {'x':'width','y':'height'}[scrollType],
            cssStyle = {'x':'left','y':'top'}[scrollType],
            scrollBar = $(s.scrollBar),
            scrollBarShow = s.scrollBarShow===under ? 1 : s.scrollBarShow,//是否一直显示滚动条
            scrollBarOuter = scrollBar.parent(),
            scrollWrap = $(s.scrollWrap),
            scrollWrapSize = scrollWrap[size](),
            scrollPanel = $(scrollPanel),
            slll = scrollPanel[size]()-scrollWrap[size](),
            next = $(s.next),
            prev = $(s.prev),
            drag = 0,
            nextTime,
            prevTime,
            animateTime;

        function _scrollbar(){
            var self = this;
            if (!(self instanceof _scrollbar)) {
                return new _scrollbar();
            };
            this.init();
        };
        $.extend(_scrollbar.prototype,{
            init:function(){
                var scrollBarSize,self=this;
                scrollPanel.css(cssStyle,0);
                scrollWrap.css({"overflow":"hidden"});
                if(slll<=0){
                    if(!scrollBarShow) scrollBarOuter.css({"display":'none'});
                    scrollBar.css(cssStyle,0).css(size,scrollWrapSize+'px');
                    return false;
                };
                scrollBarOuter.css({"display":'block'});
                scrollBarSize=Math.floor((scrollWrapSize*scrollWrapSize)/(scrollWrapSize+slll));
                scrollBar.css(cssStyle,0).css(size,scrollBarSize<36 ? '36px' : scrollBarSize+'px')
                this.drag(scrollBar,{
                    offsetParent : scrollBarOuter,
                    yLocked : scrollType === 'x' ? 1 :0,
                    xLocked : scrollType === 'x' ? 0 :1,
                    moving : function(left,top){
                        var c = scrollType === 'x' ? left : top;
                        scrollPanel.css(cssStyle,-self.bar2panel(c)+'px');
                    }
                });
                this.next();
                this.prev();
            },
            panel2bar:function(n){
                return Math.ceil(((scrollBarOuter[size]()-scrollBar[size]())*n)/slll);
            },
            bar2panel:function(n){
                return Math.ceil((slll*n)/(scrollBarOuter[size]()-scrollBar[size]()));
            },
            clickStop:function(){
                nextTime && clearInterval(nextTime);
                prevTime && clearInterval(prevTime);
                window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
            },
            clickScroll:function(direction,stopFG){
                var self=this,n=Math.abs(parseInt(scrollPanel.css(cssStyle),10)) || 0,
                    dir=direction=='next',
                    s=stopFG!==under ? (stopFG>slll ? slll : stopFG ):slll;
                nextTime && clearInterval(nextTime);
                prevTime && clearInterval(prevTime);
                animateTime && animateTime.stop();
                if(!stopFG){
                    nextTime=setInterval(function(){
                        n=n+(dir ? 10 : -10);
                        if(dir ? (n>s) : (n<0)) {
                            clearInterval(nextTime);
                            n=s;
                            n=dir ? s : 0;
                        }
                        scrollPanel.css(cssStyle,-n+'px');
                        scrollBar.css(cssStyle,self.panel2bar(n)+'px');
                    },15);
                }else{
                    var animateCSS ={};
                    animateCSS[cssStyle] = -s+'px';
                    animateTime=scrollPanel.animate(
                        animateCSS,
                        {
                            duration:500,
                            step: function(left){
                                scrollBar.css(cssStyle,-self.panel2bar(left)+'px');
                            },
                            complete: function(){
                                scrollBar.css(cssStyle,self.panel2bar(s)+'px');
                            },
                            "easing": "linear"
                        }
                    );
                }
            },
            drag:function(dragTigger,config){
                var self=this,
                    dragTigger = $(dragTigger),
                    config = config  || {},
                    offsetParent = config.offsetParent ? dragTigger.parents(config.offsetParent) : $('body'),
                    ol,
                    ot,
                    ow,
                    oh;
                dragTigger.mousedown(function(e){
                    var cx=e.clientX,cy=e.clientY,self=$(this);
                    ol=self.offset().left;
                    ot=self.offset().top;
                    self.css({'position':'absolute'});
                    ow=cx-ol;
                    oh=cy-ot;
                    self.css({'left':cx-ow-offsetParent.offset().left+'px','top':cy-oh-offsetParent.offset().top+'px'});
                    if(document.all){
                        this.setCapture();
                    }else{
                        e.preventDefault();
                    };
                    drag=1;
                });
                $(document).mousemove(function(e){
                    if(drag){
                        var cx=e.clientX,cy=e.clientY,
                            left=cx-ow-offsetParent.offset().left,
                            top=cy-oh-offsetParent.offset().top,
                            css = {},
                            dragTiggerWidth = dragTigger.width(),
                            dragTiggerHeight = dragTigger.height(),
                            offsetParentWidth = offsetParent.width(),
                            offsetParentHeight = offsetParent.height();
                        if(!config.xLocked){
                            if(left<0){
                                left=0;
                            };
                            if((left+dragTiggerWidth)>=offsetParentWidth){
                                left=offsetParentWidth - dragTiggerWidth;
                            };
                            css.left = left+'px';
                        };
                        if(!config.yLocked){
                            if(top<0){
                                top=0;
                            };
                            if((top+dragTiggerHeight) >= offsetParentHeight){
                                top=offsetParentHeight-dragTiggerHeight;
                            };
                            css.top = top+'px';
                        };
                        config.moving && config.moving.call(dragTigger,left,top);
                        dragTigger.css(css);
                        //清除选择
                        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
                    }
                });
                $(document).mouseup(function(){
                    if(drag){
                        if(document.all){
                            dragTigger[0].releaseCapture();
                        }
                        config.movend && config.movend();
                        drag=0;
                    };
                });
            },
            next : function(){
                var self=this;
                if(next){
                    next.mousedown(function(e){
                        self.clickScroll('next');
                        e.preventDefault();
                    });
                    next.mouseup(function(){self.clickStop()});
                };
            },
            prev : function(){
                var self=this;
                if(prev){
                    prev.mousedown(function(e){
                        self.clickScroll('prev');
                        e.preventDefault();
                    });
                    prev.mouseup(function(){self.clickStop()});
                }
            }
        });
        return _scrollbar();
    };
    function scrollbarOnly(elem,option){
        var elem = $(elem),data = elem.data('scrollbar');
        !data && elem.data('scrollbar',(data=scrollbar(elem,option)));
        return data;
    };
    S.scrollbar = function(scrollPanel,s){
        return scrollbarOnly(scrollPanel,s);
    };
    S.fn.scrollbar = function(s){
        return scrollbarOnly(this,s);
    };
    $(function (){
        var $document = $(document);
        if(!$document.data("data-scrollbar")){
            $document.delegate('[data-scrollbar]', 'click', function () {
                var $this = $(this), href
                    , $target = $($this.attr('data-scrollbar') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
                    , options = !$target.data('modal') && $.extend({}, $target.data(), $this.data());
                $target.scrollbar(options);
                return false
            });
            $document.data("data-scrollbar",1);
        }
    });
})($);
